using UnityEngine;
using System.Collections;

[RequireComponent(typeof(BoxCollider))]
public class GameCha : GameEntity {
	
	public enum ChaState{
		
		/// <summary>
		/// Constant idle for character
		/// </summary>
		Idle,
		
		/// <summary>
		/// Constant move for character
		/// </summary>
		Move,
		
		/// <summary>
		/// Constant attack for character
		/// </summary>
		Attack,
	};
	
	/// <summary>
	/// The state of the m.
	/// </summary>
	private ChaState mState = ChaState.Idle;
	
	/// <summary>
	/// The right or left forward
	/// </summary>
	private bool mRightOrLeft = true;
	
	private Vector3 mMoveDst = Vector3.zero;
	private Vector3 mMoveDir  = Vector3.zero;
	
	/// <summary>
	/// The m move speed.
	/// </summary>
	private float mMoveSpeed = 2.0f;
	
	/// <summary>
	/// Gets or sets the state.
	/// </summary>
	/// <value>
	/// The state.
	/// </value>
	public ChaState State{
		get{return mState;}
		set{mState = value;}
	}
	
	/// <summary>
	/// Gets or sets the move speed.
	/// </summary>
	/// <value>
	/// The move speed.
	/// </value>
	public float MoveSpeed{
		get{return mMoveSpeed;}
		set{mMoveSpeed = value;}
	}
	
	// Use this for initialization
	public override void Start () {
		base.Start();
	}
	
	/// <summary>
	/// Moves to.
	/// </summary>
	/// <param name='_dst'>
	/// _dst.
	/// </param>
	public virtual void MoveTo(Vector3 _dst){
		mMoveDst	= _dst;
		State 		= ChaState.Move;
		
		mMoveDir	 = _dst - gameObject.transform.localPosition;
		mMoveDir.Normalize();
		
		mRightOrLeft = (mMoveDst.x >= gameObject.transform.localPosition.x);		
	}
	
	// Update is called once per frame
	public override void Update () {
		base.Update();
		
		switch(mState){
		case ChaState.Idle:
			break;
		case ChaState.Move:
			ProcessMove();
			break;
		case ChaState.Attack:
			break;
		}

		// adujst rotation by camera
		if(Camera.main != null ){
			if(mRightOrLeft){
				gameObject.transform.forward = Camera.main.transform.forward;
			}else{
				gameObject.transform.forward = -Camera.main.transform.forward;
			}
		}		
	}
	
	protected virtual void ProcessMove(){
		
		Vector3 pos = gameObject.transform.localPosition + Time.deltaTime * mMoveDir * MoveSpeed;
		Vector3 dir = (mMoveDst - pos);
		if(dir.magnitude <= 0.05f || Vector3.Dot(dir,mMoveDir) < 0){
			pos		= mMoveDst;
			State	= ChaState.Idle;
		}
		
		gameObject.transform.localPosition = pos;		
	}
}
